package com.ctl.algorithm;

/**
 * <p>Title: Test3</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2019</p>
 * <p>Company: www.ctl.com</p>
 * 两个线程交叉顺序打印1到100
 * @author ctl
 * @version 1.1
 * @date 2024-07-15 15:43
 */
public class AlternatePrinting {
    private static final Object lock = new Object();
    private static int count = 1;

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Printer(), "Thread-1");
        Thread thread2 = new Thread(new Printer(), "Thread-2");

        thread1.start();
        thread2.start();
    }

    static class Printer implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 50; i++) {
                synchronized (lock) {
                    lock.notify();
                    System.out.println(Thread.currentThread().getName() + ": " + count++);
                    try {
                        if(i!=49){
                            lock.wait();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
